#include "titan.h"
#include "ui_titan.h"
#include <QDebug>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QJsonObject>


Titan::Titan(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Titan)
{
    ui->setupUi(this);
    fmt = new Format(this);

    socket = new QTcpSocket();
    connect(socket,SIGNAL(connected()),this,SLOT(on_connected()));
    connect(socket,SIGNAL(readyRead()),this,SLOT(on_read()));
    connect(socket,SIGNAL(disconnected()),this,SLOT(on_disconnected()));
    connect(socket,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(on_error(QAbstractSocket::SocketError)));
    socket->connectToHost("10.211.55.3",9988,QTcpSocket::ReadWrite);

    check_timer = new QTimer(this);
    connect(check_timer,SIGNAL(timeout()),this,SLOT(on_check_timer()));
    check_timer->start(5000);


    ui->send_msg_edt->installEventFilter(this);
}

Titan::~Titan()
{
    delete ui;
}

void Titan::on_connected()
{
    qDebug()<<"connect success!!!";
    reconnect_flag = 0;
    if(is_login){
        socket->write(fmt->login_data(name,passwd));
    }
}

void Titan::on_read()
{
    QByteArray data = socket->readAll();
    qDebug() << data;
    QJsonParseError json_error;
    QJsonDocument parse_doucment = QJsonDocument::fromJson(data, &json_error);
    if(json_error.error != QJsonParseError::NoError){
        return;
    }
    if(!parse_doucment.isObject()){
        return;
    }
    QJsonObject obj = parse_doucment.object();
    QString rep = obj.take("rep").toString();
    QString code = obj.take("status").toObject().take("code").toString();
    if(rep == "login"){
        if(code == "10000"){
            token = obj.take("token").toString();
            uid = obj.take("uid").toString();
            ui->stackedWidget->setCurrentIndex(1);
            name = ui->u_name_edt->text();
            passwd = ui->u_passwd_edt->text();
            is_login = 1;
            ui->msg_edt->setText("-- 登录成功 --");
        }
    }else if(rep == "recv_msg"){
        QString msg = obj.take("data").toString();
        if(msg.isEmpty()){
            return;
        }
        ui->recv_msg_edt->setText(msg);
    }
}

void Titan::on_disconnected(){
    qDebug()<<"disconnect!!!";
    reconnect_flag = 1;
}

void Titan::on_error(QAbstractSocket::SocketError _err)
{
    reconnect_flag = 1;
}

void Titan::on_check_timer()
{
    int size = socket->write(fmt->check_conn_data());
    if(size < 0){
        reconnect_flag = 1;
    }
    if(reconnect_flag){
        reconnect();
    }
}


/**
 * @brief Titan::reconnect
 * @details 断线重连
 */
void Titan::reconnect()
{
    qDebug()<<"reconnect...";
    socket->close();
    socket->abort();
    socket->connectToHost("10.211.55.3",9988,QTcpSocket::ReadWrite);
}

void Titan::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Return){
        if(ui->stackedWidget->currentIndex()==0){
            on_loginBtn_clicked();
        }
    }
}

bool Titan::eventFilter(QObject *obj, QEvent *e)
{
    if (e->type() == QEvent::KeyPress)
    {
        QKeyEvent *event = static_cast<QKeyEvent*>(e);
        if (event->key() == Qt::Key_Return)
        {
            if(obj == ui->send_msg_edt){
                if(ui->send_msg_edt->toPlainText().isEmpty()){
                    return true;
                }
                if(ui->send_msg_edt->toPlainText().at(0) == "@"){
                    recver = ui->send_msg_edt->toPlainText().mid(1);
                    ui->msg_edt->setText(QString("发送数据给:%1").arg(recver));
                }{
                    socket->write(fmt->msg_data(token,recver,ui->send_msg_edt->toPlainText()));
                }
                ui->send_msg_edt->clear();
                return true;
            }
        }
    }
    return false;
}


/**
 * @brief Titan::on_loginBtn_clicked
 * @details 用户登录
 */
void Titan::on_loginBtn_clicked()
{
    if(ui->u_name_edt->text().isEmpty() || ui->u_passwd_edt->text().isEmpty()){
        return;
    }
    socket->write(fmt->login_data(ui->u_name_edt->text(),ui->u_passwd_edt->text()));
}


/**
 * @brief Titan::on_regBtn_clicked
 * @details 用户注册
 */
void Titan::on_regBtn_clicked()
{
    if(ui->u_name_edt->text().isEmpty() || ui->u_passwd_edt->text().isEmpty()){
        return;
    }
    socket->write(fmt->reg_data(ui->u_name_edt->text(),ui->u_passwd_edt->text()));
}
